import os
import json
from datetime import datetime
from utils.common import CommonUtils

class TaskTracker:
    def __init__(self, task_name, logger):
        self.task_name = task_name
        self.logger = logger
        self.reports_dir = os.path.join('reports', self.task_name)
        self.task_status_file = os.path.join(self.reports_dir, 'task_status.json')
        self.task_status = {
            'task_name': task_name,
            'start_time': None,
            'end_time': None,
            'status': 'pending',  # pending, running, completed, failed
            'tables': {},
            'views': [],
            'resume_info': {},
            'error': None,
            'migration_results': {
                'success_tables': [],
                'failed_tables': [],
                'total_tables': 0,
                'total_records_migrated': 0
            }
        }
        
        # 确保报告目录存在
        CommonUtils.ensure_directory_exists(self.reports_dir)
        
        # 加载已有的任务状态
        self.load_task_status()
    
    def start_task(self):
        """
        开始任务
        """
        self.task_status['start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.task_status['status'] = 'running'
        self.save_task_status()
        self.logger.info(f"任务开始: {self.task_name}")
    
    def finish_task(self, success=True, error=None):
        """
        完成任务
        """
        self.task_status['end_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.task_status['status'] = 'completed' if success else 'failed'
        self.task_status['error'] = error
        self.save_task_status()
        
        if success:
            self.logger.info(f"任务完成: {self.task_name}")
        else:
            self.logger.error(f"任务失败: {self.task_name}, 错误: {error}")
    
    def set_tables(self, tables):
        """
        设置需要迁移的表
        """
        for table_name in tables:
            if table_name not in self.task_status['tables']:
                self.task_status['tables'][table_name] = {
                    'status': 'pending',  # pending, migrating, completed, failed
                    'start_time': None,
                    'end_time': None,
                    'source_count': 0,
                    'target_count': 0,
                    'last_row': 0,
                    'error': None
                }
        self.save_task_status()
    
    def set_views(self, views):
        """
        设置需要处理的视图
        """
        self.task_status['views'] = views
        self.save_task_status()
    
    def start_table_migration(self, table_name):
        """
        开始表迁移
        """
        if table_name in self.task_status['tables']:
            self.task_status['tables'][table_name]['status'] = 'migrating'
            self.task_status['tables'][table_name]['start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.save_task_status()
    
    def finish_table_migration(self, table_name, success=True, source_count=0, target_count=0, error=None):
        """
        完成表迁移
        """
        if table_name in self.task_status['tables']:
            self.task_status['tables'][table_name]['status'] = 'completed' if success else 'failed'
            self.task_status['tables'][table_name]['end_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.task_status['tables'][table_name]['source_count'] = source_count
            self.task_status['tables'][table_name]['target_count'] = target_count
            self.task_status['tables'][table_name]['error'] = error
            self.save_task_status()
    
    def update_table_progress(self, table_name, last_row):
        """
        更新表迁移进度
        """
        if table_name in self.task_status['tables']:
            self.task_status['tables'][table_name]['last_row'] = last_row
            # 更新续传信息
            self.task_status['resume_info'][table_name] = {
                'last_row': last_row
            }
            self.save_task_status()
    
    def set_migration_results(self, results):
        """
        设置迁移结果
        """
        self.task_status['migration_results'] = results
        self.save_task_status()
    
    def get_task_status(self):
        """
        获取任务状态
        """
        return self.task_status
    
    def get_resume_info(self):
        """
        获取续传信息
        """
        return self.task_status['resume_info']
    
    def load_task_status(self):
        """
        加载任务状态
        """
        try:
            status = CommonUtils.read_json_file(self.task_status_file)
            if status:
                self.task_status = status
                self.logger.info(f"加载任务状态成功: {self.task_name}")
                
                # 如果任务状态是running，说明上次迁移中断，需要续传
                if self.task_status.get('status') == 'running':
                    self.logger.warning(f"检测到上次迁移中断，准备从断点处续传")
        except Exception as e:
            self.logger.warning(f"加载任务状态失败，将创建新的任务状态: {e}")
    
    def save_task_status(self):
        """
        保存任务状态
        """
        try:
            CommonUtils.write_json_file(self.task_status_file, self.task_status)
        except Exception as e:
            self.logger.error(f"保存任务状态失败: {e}")
    
    def get_pending_tables(self):
        """
        获取待迁移的表
        """
        pending_tables = []
        for table_name, table_info in self.task_status['tables'].items():
            if table_info['status'] in ['pending', 'failed']:
                pending_tables.append(table_name)
        return pending_tables
    
    def generate_report(self):
        """
        生成迁移报告
        """
        report_file = os.path.join(self.reports_dir, 'migration_report.json')
        
        # 计算统计信息
        stats = {
            'total_tables': len(self.task_status['tables']),
            'success_tables': sum(1 for t in self.task_status['tables'].values() if t['status'] == 'completed'),
            'failed_tables': sum(1 for t in self.task_status['tables'].values() if t['status'] == 'failed'),
            'pending_tables': sum(1 for t in self.task_status['tables'].values() if t['status'] == 'pending'),
            'migrating_tables': sum(1 for t in self.task_status['tables'].values() if t['status'] == 'migrating'),
            'total_views': len(self.task_status['views']),
            'total_records_migrated': self.task_status['migration_results'].get('total_records_migrated', 0)
        }
        
        # 构建报告内容
        report = {
            'task_name': self.task_name,
            'start_time': self.task_status['start_time'],
            'end_time': self.task_status['end_time'],
            'status': self.task_status['status'],
            'statistics': stats,
            'tables_detail': self.task_status['tables'],
            'views': self.task_status['views'],
            'error': self.task_status['error']
        }
        
        try:
            CommonUtils.write_json_file(report_file, report)
            self.logger.info(f"迁移报告生成成功: {report_file}")
            return report
        except Exception as e:
            self.logger.error(f"迁移报告生成失败: {e}")
            return None